package com.szh.mysobproject.paging.source

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.szh.mysobproject.execption.ServiceException
import com.szh.mysobproject.model.UserQa
import com.szh.mysobproject.viewmodel.app.QaNetWork
import timber.log.Timber

class UserQaPagingSource(private val userId: String) : PagingSource<Int, UserQa.Content>() {
    override fun getRefreshKey(state: PagingState<Int, UserQa.Content>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UserQa.Content> {
        return try {
            val page = params.key ?: FIRST_PAGE
            Timber.d("load :=====  userId is $userId page is  $page")
            val response = QaNetWork.loadUserQaList(userId, page)
            val responseDate = response.getData()
            val prevKey = if (responseDate.first) null else page - 1
            val nextKey = if (responseDate.last) null else page + 1
            if (response.isSuccess()) LoadResult.Page(
                data = responseDate.content,
                prevKey = prevKey,
                nextKey = nextKey
            ) else LoadResult.Error(ServiceException())
        } catch (t: Throwable) {
            t.printStackTrace()
            LoadResult.Error(t)
        }
    }

    companion object {
        private const val FIRST_PAGE = 1
    }
}